import { createServer } from "node:http";
import dotenv from "dotenv";
import path from "node:path";
import url from "node:url";
import fs from "node:fs/promises";
import contentTypeMiddleware from "./middleware.js";

// 加载配置
dotenv.config();
const PORT = process.env.PORT || 8002;

const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// 处理为当前public文件夹路径
const resourcePath = path.join(__dirname, "public");

const server = createServer((req, res) => {
  res.setHeader
  console.log(`Receive request ${req.url} ${new Date()}`);
  // middleware的思想来处理contentType
  contentTypeMiddleware(req, res, async () => {
    try {
        // 拼接路径
        const filePath = path.join(resourcePath, req.url);
        // 读取文件
        const data = await fs.readFile(filePath);
        res.end(data);
    } catch (error) {
      console.log("出错"+req.url)
    }
  });
});

server.listen(PORT, () => {
  console.log(`Server run At: http://localhost:${PORT}`);
});
